package com.whfc.fse.queue;

import com.alibaba.fastjson.JSON;
import com.whfc.common.constant.QueueConst;
import com.whfc.common.enums.NetState;
import com.whfc.common.util.DateUtil;
import com.whfc.fse.dao.FseCraneDataMapper;
import com.whfc.fse.dao.FseCraneMapper;
import com.whfc.fse.dao.FseSyncDao;
import com.whfc.fse.dto.FseCraneDataDTO;
import com.whfc.fse.dto.FseWarnDTO;
import com.whfc.fse.entity.FseCrane;
import com.whfc.fse.entity.FseCraneData;
import com.whfc.fse.entity.FseDeviceCraneDataLog;
import com.whfc.fse.entity.FseSync;
import com.whfc.fse.enums.FseType;
import com.whfc.fse.enums.FseWarnRuleType;
import com.whfc.fse.manager.FseWarnMgr;
import com.whfc.fse.pushPlatform.ShengSiFseApi;
import com.whfc.fse.pushPlatform.ShiShouFseApi;
import com.whfc.fse.pushPlatform.model.ShiShouCraneRealDTO;
import com.whfc.fse.pushPlatform.model.ShiShouCraneWarnDTO;
import com.whfc.influx.dao.FseCraneDataLogDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 处理硬件上传的塔机实时数据
 *
 * @author sun_guodong
 * @date 2020-05-26
 */
@Component
@RabbitListener(queuesToDeclare = {@Queue(name = QueueConst.FSE_CRANE_REAL_DATA)}, concurrency = "1-2",containerFactory = "baseFactory")
public class FseCraneRealDataQueueListener {
    private static final Logger logger = LoggerFactory.getLogger(FseCraneRealDataQueueListener.class);

    @Autowired
    private FseCraneMapper fseCraneMapper;

    @Autowired
    private FseSyncDao fseSyncDao;

    @Autowired
    private FseCraneDataMapper fseCraneDataMapper;

    @Autowired
    private FseCraneDataLogDao fseCraneDataLogDao;

    @Autowired
    private FseWarnMgr fseWarnMgr;

    @Autowired
    private ShiShouFseApi shiShouFseApi;

    @Autowired
    private ShengSiFseApi shengSiFseApi;

    @RabbitHandler
    public void handle(String msg) {
        try {
            logger.info("消息消费者处理塔机实时数据,msg:{}", msg);
            FseCraneDataDTO fseCraneDeviceData = JSON.parseObject(msg, FseCraneDataDTO.class);
            String sn = fseCraneDeviceData.getSn();
            String platform = fseCraneDeviceData.getPlatform();
            FseCrane fseCrane = fseCraneMapper.selectByPlatformAndSn(platform, sn);
            if (fseCrane == null) {
                logger.warn("该塔机不存在,platform:{},sn:{}", platform, sn);
                return;
            }
            Integer craneId = fseCrane.getId();
            // 插入塔机数据
            FseCraneData fseCraneData = new FseCraneData();
            BeanUtils.copyProperties(fseCraneDeviceData, fseCraneData);
            fseCraneData.setCraneId(craneId);
            fseCraneDataMapper.updateByCraneId(fseCraneData);

            // 更新设备在线状态
            Date time = fseCraneDeviceData.getTime();
            int netState = NetState.OFFLINE.getValue();
            if (DateUtil.isToday(time)) {
                netState = NetState.ONLINE.getValue();
            }
            logger.info("时间==========time：{}，塔机状态=============netState：{}", time, netState);
            fseCrane.setNetState(netState);
            fseCraneMapper.updateByPrimaryKeySelective(fseCrane);

            // 插入fse_device_crane_data_log
            FseDeviceCraneDataLog fseDeviceCraneDataLog = new FseDeviceCraneDataLog();
            BeanUtils.copyProperties(fseCraneDeviceData, fseDeviceCraneDataLog);
            fseDeviceCraneDataLog.setCraneId(craneId);
            fseCraneDataLogDao.insert(fseDeviceCraneDataLog);

            // 获取同步配置
            Integer deptId = fseCrane.getDeptId();
            List<Integer> platforms = new ArrayList();
            platforms.add(1);
            platforms.add(3);
            List<FseSync> list = fseSyncDao.seiectByDeptIdAndPlatforms(deptId,platforms);
            if (list.size() > 0) {
                for (FseSync fseSync : list) {
                    switch (fseSync.getPlatform()) {
                        // 石首塔吊平台推送
                        case 1:
                            ShiShouCraneRealDTO shiShouCraneRealDTO = new ShiShouCraneRealDTO();
                            shiShouCraneRealDTO.setRecDate(DateUtil.formatDate(time, "yyyy-MM-dd HH:mm:ss"));
                            shiShouCraneRealDTO.setDeviceId(sn);
                            shiShouCraneRealDTO.setCreanceId(sn);
                            shiShouCraneRealDTO.setCraneLoad(fseCraneDeviceData.getWeight());
                            shiShouCraneRealDTO.setRatedKn(fseCraneDeviceData.getMomentRatio());
                            shiShouCraneRealDTO.setAngle(fseCraneDeviceData.getDipAngle());
                            shiShouCraneRealDTO.setRadius(fseCraneDeviceData.getRange());
                            shiShouCraneRealDTO.setHeight(fseCraneDeviceData.getHeight());
                            shiShouCraneRealDTO.setWindSpeed(fseCraneDeviceData.getWindSpeed());
                            shiShouCraneRealDTO.setRotation(fseCraneDeviceData.getTurnAngle());
                            shiShouCraneRealDTO.setCurrentMaxLoad(fseCraneDeviceData.getMaxWeight());
                            shiShouCraneRealDTO.setIsOnline("1");
                            shiShouCraneRealDTO.setDriverId("吴军");
                            shiShouFseApi.reportRealCrane(shiShouCraneRealDTO, fseSync);
                            break;
                        // 升思塔吊平台推送
                        case 3:
                            shengSiFseApi.pushCraneRealData(fseCraneDeviceData);
                            break;
                    }
                }
            }

            if (fseCraneDeviceData.getCraneStatus() == null) {
                return;
            }
            // 处理报警数据
            FseWarnRuleType fseWarnRuleType = FseWarnRuleType.parseByValue(fseCraneDeviceData.getCraneStatus());
            if (fseWarnRuleType != null || StringUtils.hasText(fseCraneDeviceData.getAlarmCause())) {
                String triggerValue = this.getTriggerValue(fseWarnRuleType, fseCraneDeviceData);
                FseWarnDTO fseWarnDTO = new FseWarnDTO();
                fseWarnDTO.setDeptId(fseCrane.getDeptId());
                fseWarnDTO.setCode(fseCrane.getCode());
                fseWarnDTO.setFseType(FseType.CRANE);
                fseWarnDTO.setFseWarnRuleType(fseWarnRuleType);
                fseWarnDTO.setTriggerTime(time);
                fseWarnDTO.setTriggerObjectId(fseCrane.getId());
                fseWarnDTO.setTriggerValue(triggerValue);
                fseWarnMgr.handleFseWarn(fseWarnDTO);

                if (list.size() > 0) {
                    for (FseSync fseSync : list) {
                        switch (fseSync.getPlatform()) {
                            // 石首平台推送报警
                            case 1:
                                ShiShouCraneWarnDTO shiShouCraneWarnDTO = new ShiShouCraneWarnDTO();
                                shiShouCraneWarnDTO.setTime(DateUtil.formatDate(time, "yyyy-MM-dd HH:mm:ss"));
                                shiShouCraneWarnDTO.setCraneNum(sn);
                                shiShouCraneWarnDTO.setInformation(triggerValue);
                                shiShouFseApi.reportCraneViolation(shiShouCraneWarnDTO,fseSync);
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("消息消费者处理塔机实时数据失败", e);
        }
    }

    /**
     * 获取触发值
     *
     * @param ruleType
     * @param fseCraneDataDTO
     * @return
     */
    private String getTriggerValue(FseWarnRuleType ruleType, FseCraneDataDTO fseCraneDataDTO) {
        String triggerValue = "";
        switch (ruleType) {
            case CRANE_WEIGHT:
                triggerValue = String.valueOf(fseCraneDataDTO.getWeight());
                break;
            case CRANE_RANGE:
                triggerValue = String.valueOf(fseCraneDataDTO.getRange());
                break;
            case CRANE_HEIGHT_RANGE:
                triggerValue = String.valueOf(fseCraneDataDTO.getHeight());
                break;
            case CRANE_ROTARY_LIMIT:
                triggerValue = String.valueOf(fseCraneDataDTO.getTurnAngle());
                break;
            case CRANE_WIND_SPEED:
                triggerValue = String.valueOf(fseCraneDataDTO.getWindSpeed());
                break;
            case CRANE_TURN:
                triggerValue = String.valueOf(fseCraneDataDTO.getDipAngle());
                break;
            default:
                triggerValue = "";
                break;
        }
        return triggerValue;

    }

}
